// listen-word.js - 听单词模式组件逻辑
Component({
  data: {
    listenOptions: [],
    isPlaying: false,
    audioContext: null
  },

  lifetimes: {
    attached: function() {
      // 初始化音频上下文
      this.initAudioContext();
    },
    detached: function() {
      // 清理音频上下文
      if (this.data.audioContext) {
        this.data.audioContext.destroy();
        this.setData({ audioContext: null, isPlaying: false });
      }
    }
  },

  methods: {
    // 初始化音频上下文
    initAudioContext: function() {
      if (!this.data.audioContext) {
        const audioContext = wx.createInnerAudioContext();
        this.setData({ audioContext });

        // 设置音频上下文事件监听
        audioContext.onPlay(() => {
          this.setData({ isPlaying: true });
        });

        audioContext.onEnded(() => {
          this.setData({ isPlaying: false });
        });

        audioContext.onError((error) => {
          console.error('音频播放错误:', error);
          this.setData({ isPlaying: false });
          wx.showToast({
            title: '播放失败',
            icon: 'none',
            duration: 2000
          });
        });

        audioContext.onStop(() => {
          this.setData({ isPlaying: false });
        });
      }
    },

    // 生成听力选项
    generateListenOptions: function() {
      const currentWord = this.properties.currentWord;
      const allWords = this.properties.words;
      
      if (!currentWord || !currentWord.english || !allWords || allWords.length === 0) {
        console.warn('生成听力选项失败：缺少必要的单词数据');
        return;
      }

      const options = [currentWord.english];
      
      // 随机选择其他3个单词作为干扰选项
      while (options.length < 4) {
        const randomIndex = Math.floor(Math.random() * allWords.length);
        const randomWord = allWords[randomIndex].word;
        if (!options.includes(randomWord)) {
          options.push(randomWord);
        }
      }
      
      // 打乱选项顺序
      for (let i = options.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [options[i], options[j]] = [options[j], options[i]];
      }
      
      this.setData({ listenOptions: options });
    },

    // 获取单词音频URL
    getAudioUrl: function(word, type) {
      const currentWord = this.properties.currentWord;

      // 检查currentWord是否有pronunciation字段和audio子字段
      if (currentWord && currentWord.pronunciation && currentWord.pronunciation.audio) {
        const audioUrls = currentWord.pronunciation.audio;

        // 根据类型返回对应的音频URL
        if (type === 'american' && audioUrls.us) {
          return audioUrls.us;
        } else if (type === 'british' && audioUrls.uk) {
          return audioUrls.uk;
        }
      }

      // 如果没有找到音频URL，记录警告并返回null
      console.warn(`未找到单词 ${word} 的${type}发音音频资源`);
      return null;
    },

    // 播放发音
    playListenPronunciation: function() {
      const speed = this.properties.playbackSpeed;
      const type = this.properties.pronunciationType;
      const currentWord = this.properties.currentWord;

      if (!currentWord || !currentWord.english) {
        wx.showToast({
          title: '当前没有单词可播放',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 如果正在播放，先停止当前播放
      if (this.data.isPlaying && this.data.audioContext) {
        this.data.audioContext.stop();
      }

      // 获取音频URL
      const audioUrl = this.getAudioUrl(currentWord.english, type);

      if (!audioUrl) {
        wx.showToast({
          title: '音频资源不存在',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 确保audioContext存在
      if (!this.data.audioContext) {
        this.initAudioContext();
        if (!this.data.audioContext) {
          wx.showToast({
            title: '音频初始化失败',
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }

      // 设置音频属性
      this.data.audioContext.src = audioUrl;
      this.data.audioContext.playbackRate = speed;
      this.data.audioContext.volume = 1.0;

      // 开始播放
      try {
        const playPromise = this.data.audioContext.play();

        // 检查是否返回Promise
        if (playPromise && typeof playPromise.then === 'function') {
          playPromise.then(() => {
            this.setData({ isPlaying: true });
            console.log(`开始播放: ${currentWord.english} (${type}, ${speed}x)`);
          }).catch((error) => {
            console.error('播放失败:', error);
            this.setData({ isPlaying: false });
            wx.showToast({
              title: '播放失败',
              icon: 'none',
              duration: 2000
            });
          });
        } else {
          // 如果不是Promise，直接设置状态
          this.setData({ isPlaying: true });
          console.log(`开始播放: ${currentWord.english} (${type}, ${speed}x)`);
        }
      } catch (error) {
        console.error('播放调用失败:', error);
        this.setData({ isPlaying: false });
        wx.showToast({
          title: '播放失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 选择听力选项
    selectListenOption: function(e) {
      const selectedIndex = e.currentTarget.dataset.index;
      const selectedWord = this.data.listenOptions[selectedIndex];
      const correctWord = this.properties.currentWord.english;
      
      if (selectedWord === correctWord) {
        wx.showToast({
          title: '回答正确！',
          icon: 'success'
        });
        
        // 可以自动标记为已学
        setTimeout(() => {
          this.triggerEvent('listencomplete', { result: 'correct', word: correctWord });
        }, 1500);
      } else {
        wx.showToast({
          title: '回答错误，再试一次',
          icon: 'none'
        });
      }
    },

    // 退出听力模式
    exitListenMode: function() {
      this.triggerEvent('exit', {});
    }
  }
});